<template>
	<view class="my_container">
		<!-- <CustomNavbarTwo :title="pageTitle" :style="navbarStyle" /> -->
		<view class="my_container_body">
			<view class="my_container_body_head"></view>
			<view class="my_container_body_body">
				<view class="login-wrap">
					<button class="button1" v-if="!isAggree || isPhone" @tap="handleClick">一键登录</button>
					<button class="button1" v-else open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">一键登录</button>
					<button @tap="handleBack" class="button1 button2">取消登录</button>
				</view>
				<view class="agreement-container">
					<!-- 勾选框与协议文本 -->
					<view class="agreement-box">
						<checkbox-group @change="toggleAgreement">
							<checkbox style="transform: scale(0.55)" :checked="isAggree" color="#007AFF" />
						</checkbox-group>
						<text class="agreement-text">
							<text @tap="toggleAgreement">我已阅读并同意</text>
							<text class="link-text" @tap.stop="navigateTo('userAgreement')">《用户协议》</text>
							<text class="separator">、</text>
							<text class="link-text" @tap.stop="navigateTo('privacyPolicy')">《隐私政策》</text>
						</text>
					</view>
				</view>
			</view>
			<u-modal :show="show" :title="title" @confirm="confirm"></u-modal>
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog
					cancelText="不同意"
					confirmText="同意"
					title="温馨提示"
					content="已阅读并同意用户协议和隐私政策"
					@confirm="dialogConfirm"
					@close="dialogClose"
				></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>
<script>
import CustomNavbarTwo from '@/components/CustomNavbarTwo.vue';
import store from '../../store/index.js';
import { mapState } from 'vuex'; // 关键导入
export default {
	components: { CustomNavbarTwo },
	data() {
		return {
			isAgreed: false,
			pageTitle: '登录',
			navbarStyle: {
				backgroundColor: 'transparent',
				color: '#fff'
			},
			show: false,
			title: '请您先同意协议！',
			xcxCode: '',
			checkboxValue1: [],
			isAggree: false,
			checkboxList: [{ name: '我已阅读并同意授权用户协议和隐私政策', disabled: false }],
			wechatUserRemote: {
				sessionKey: '',
				openId: '',
				signature: '',
				encryptedData: '',
				iv: '',
				rawData: ''
			},
			latitude: '',
			longitude: '',
			isPhone: false,
			provinceName: '',
			cityName: '',
			token: '',
			userId: '',
			userInfo: null,
			isAdmin: null
		};
	},
	onLoad() {},
	onShow() {
		// this.getMyLoction();
		this.handeUserinfo();
	},
	methods: {
		dialogClose() {
			this.$refs.alertDialog.close();
		},
		dialogConfirm() {
			this.isAggree = true;
			this.$refs.alertDialog.close();
		},
		handleClick() {
			if (this.isAggree && this.isPhone) {
				store.commit('setUserInfo', this.userInfo);
				uni.setStorageSync('token', this.token);
				uni.setStorageSync('userId', this.userId);
				uni.setStorage({
					key: 'userInfo',
					data: this.userInfo
				});
				uni.setStorage({
					key: 'isAdmin',
					data: this.isAdmin
				});
				uni.switchTab({
					url: '/pages/login/index'
				});
			} else {
				this.$refs.alertDialog.open();
			}
		},
		navigateTo(type) {
			if (type == 'userAgreement') {
				uni.navigateTo({
					url: '/page/onReady/user-agreement'
				});
			} else {
				uni.navigateTo({
					url: '/page/onReady/privacyPolicy'
				});
			}
		},
		// 勾选状态切换
		toggleAgreement() {
			this.isAggree = !this.isAggree;
		},
		//返回
		handleBack() {
			// uni.clearStorageSync();
			const pages = getCurrentPages();
			console.log(pages, 66);
			if (pages.length > 1) {
				uni.navigateBack({ delta: 1 });
			} else {
				uni.switchTab({ url: '/pages/my/index' }); // 跳转到首页或其他页面
			}
		},
		//刚进来先获取用户信息看是否绑定手机号
		handeUserinfo() {
			const _that = this;
			uni.login({
				provider: 'weixin',
				success: function (res) {
					if (res.code) {
						_that.xcxCode = res.code;
						console.log(res);
						_that.$https.post(_that.$api.login + '?xcxCode=' + res.code, {}).then((res) => {
							if (res.code === 200) {
								//判断是否绑定了手机号
								if (res.data.user.phonenumber) {
									console.log('我绑定了');
									_that.isPhone = true;
								} else {
									_that.isPhone = false;
								}
								_that.token = res.data.token;
								_that.userId = res.data.user.userId;
								_that.userInfo = res.data.user;
								_that.isAdmin = res.data.user.admin;
								_that.wechatUserRemote.sessionKey = res.data.sessionKey;
								_that.wechatUserRemote.openId = res.data.openId;
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								});
							}
						});
					}
				}
			});
		},
		// 处理手机号授权回调
		async handleGetPhoneNumber(e) {
			console.log(6666);
			if (e.detail.errMsg === 'getPhoneNumber:ok') {
				console.log(e);
				store.commit('setUserInfo', this.userInfo);
				uni.setStorageSync('token', this.token);
				uni.setStorageSync('userId', this.userId);
				uni.setStorage({
					key: 'userInfo',
					data: this.userInfo
				});
				uni.setStorage({
					key: 'isAdmin',
					data: this.isAdmin
				});
				const { code, encryptedData, iv } = e.detail;
				// 将加密数据发送到后端解密
				this.wechatUserRemote.encryptedData = encryptedData;
				this.wechatUserRemote.iv = iv;
				this.wechatUserRemote.code = code;
				this.$https.post(this.$api.xcxPhone, this.wechatUserRemote).then((res) => {
					//绑定手机号
					if (res.code === 200) {
						console.log(res, 66666);
						this.handleUpdateProfile(res.data.phoneNumber);
					} else {
						//弹窗绑定手机号
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			} else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
				uni.showToast({ title: '用户拒绝授权', icon: 'none' });
			}
		},
		//绑定手机号
		handleUpdateProfile(phone) {
			this.$https.post(this.$api.updateProfile, { phonenumber: phone }).then((res) => {
				//绑定手机号
				if (res.code === 200) {
					console.log(res, 66666);
					this.getOpenId();
				} else {
					//弹窗绑定手机号
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		getMyLoction() {
			console.log(666);
			const _that = this;
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					_that.getAddressByLanLen(res.latitude, res.longitude);
				}
			});
		},
		getAddressByLanLen(lat, lon) {
			let data = {
				lat: lat,
				lon: lon
			};
			console.log(data, 777);
			this.$https.post(this.$api.getAddressByLanLen, data).then((res) => {
				if (res.code === 200) {
					const data = res.data;
					this.provinceName = data.provinceName;
					if (data.provinceName != data.cityName) {
						this.cityName = data.cityName;
					}
					uni.setStorageSync('address', JSON.stringify(res.data));
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		confirm() {
			this.show = false;
		},
		checkboxChange(n) {
			console.log(n, this.isAggree);
			if (n.length == 1) {
				this.isAggree = true;
			} else {
				this.isAggree = false;
			}
		},
		getLoginUser(xcxCode) {
			this.$https.post(this.$api.login + '?xcxCode=' + xcxCode, {}).then((res) => {
				if (res.code === 200) {
					uni.setStorageSync('token', res.data.token);
					uni.setStorageSync('userId', res.data.user.userId);
					uni.setStorage({
						key: 'userInfo',
						data: res.data.user
					});
					uni.setStorage({
						key: 'isAdmin',
						data: res.data.user.admin
					});
					this.wechatUserRemote.sessionKey = res.data.sessionKey;
					this.wechatUserRemote.openId = res.data.openId;
					this.getUserInfo();
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		getView() {
			const _that = this;
			uni.login({
				provider: 'weixin',
				success: function (res) {
					if (res.code) {
						_that.xcxCode = res.code;
						_that.getLoginUser(res.code);
					}
				}
			});
		},
		getOpenId() {
			const _that = this;
			if (!_that.isAggree) {
				_that.show = true;
				return;
			}
			uni.login({
				provider: 'weixin',
				success: function (res) {
					if (res.code) {
						_that.xcxCode = res.code;
						// _that.getMyLoction();
						_that.getLoginUser(res.code);
					}
				}
			});
		},
		getUserInfo() {
			uni.getUserInfo({
				provider: 'weixin',
				success: (infoRes) => {
					console.log(infoRes, 66);
					this.wechatUserRemote.signature = infoRes.signature;
					this.wechatUserRemote.encryptedData = infoRes.encryptedData;
					this.wechatUserRemote.iv = infoRes.iv;
					this.wechatUserRemote.rawData = infoRes.rawData;
					this.getXcxInfo();
				}
			});
		},
		getXcxInfo() {
			this.$https.post(this.$api.xcxInfo, this.wechatUserRemote).then((res) => {
				if (res.code === 200) {
					console.log(res);
					uni.redirectTo({
						url: this.isPhone ? '/pages/login/index' : '/pages/index/user'
						// url: '/pages/index/user'
					});
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		//判断是否绑定手机号
		getXcxPhone() {
			this.wechatUserRemote.encryptedData =
				'JTdsSvNDWyqG68FCnUOHVEA7/AulFM+jr9XRtybRdthtI9VgaDI6iYan+qnsDJv0nWagp185uIKJhoz8hZp1Ok/DWK8RD8C9Y0koA+X9syAhHSK90Rkd8ZBnkzCHS8UyPfgJb78HVUFfueZRY+pfSmUuI7/4EhkUKzWFhSaTtQuPJCE3m5IdCvIa10vTpS6F+GNafuK7LHrVw0cgLwq7KA==';
			this.wechatUserRemote.iv = 'NupFOnmzoQ4qq8XicOu8cQ==';
			this.wechatUserRemote.code = 'a511005ead26da537f5f38c018a0e8d408cc2cf995bcffc7be3b1360520b0c42';
			this.$https.post(this.$api.xcxPhone, this.wechatUserRemote).then((res) => {
				if (res.code === 200) {
					console.log(res, 66666);
				} else {
					//弹窗绑定手机号
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.my_container {
	width: 100%;

	.my_container_body {
		width: 750rpx;
		height: 100vh;
		// background: linear-gradient(180deg, #ddffde 0%, #ffffff 29%, #ffffff 100%);
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		background: url('https://market-fenjie-1331975401.cos.ap-nanjing.myqcloud.com/2025/03/31/4d5aa0163a8543beb6c2e9b5bc666a8d.jpg');
		background-size: 116% 100%;
		background-position: center;
		display: flex;
		justify-content: center;

		.my_container_body_head {
			width: 686rpx;
			height: 154rpx;
		}

		.back-wrap {
			position: absolute;
			top: 80rpx;
			left: 20rpx;

			image {
				width: 100rpx;
				height: 100rpx;
			}
		}

		.my_container_body_body {
			background-color: #ffffff;
			padding-top: 50rpx;
			position: absolute;
			bottom: 150rpx;
			width: 450rpx;
			margin-left: 32rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.login-wrap {
				background-color: #ffffff;
			}

			button {
				font-size: 34rpx;
				width: 400rpx;
				height: 76rpx;
				background: #1ee825;
				border-radius: 84rpx 84rpx 84rpx 84rpx;
				// margin-left: 143rpx;
				text-align: center;
				line-height: 76rpx;
				color: #ffffff;
				// margin-top: 50rpx;
			}

			.button1 {
				width: 400rpx;
				height: 76rpx;
				line-height: 76rpx !important;
				/* 覆盖button默认样式 */
				background: #1ee825;
				border-radius: 84rpx;
				color: #ffffff;
				margin: 0;
				padding: 0;
				margin-bottom: 20rpx;

				&::after {
					border: none;
				}

				/* 去除默认边框 */
			}

			.button2 {
				background: #9f9f9f;
			}

			.youke {
				margin-top: 6rpx;
				font-size: 22rpx;
				text-decoration: underline;
			}

			::v-deep .agreement-container {
				.agreement-box {
					display: flex;
					align-items: center;

					checkbox-group {
						width: 40rpx;
					}

					.agreement-text {
						margin-left: 10rpx;
						font-size: 18rpx;
						color: #606266;
					}

					.link-text {
						color: #007aff;
						text-decoration: underline;
						margin: 0 4rpx;
					}

					.separator {
						color: #606266;
					}
				}
			}

			// .checkbox {
			// 	text-align: center;
			// 	font-size: 10rpx;
			// 	height: 50rpx;
			// 	line-height: 50rpx;
			// 	width: 60%;
			// 	// width: 480rpx;
			// 	// margin-left: 53rpx;
			// 	margin-top: 30rpx;
			// 	::v-deep .u-checkbox__icon-wrap {
			// 		width: 15px !important;
			// 		height: 15px !important;
			// 	}
			// 	::v-deep .u-checkbox {
			// 		display: flex;
			// 		justify-content: center;
			// 		text {
			// 			font-size: 20rpx !important;
			// 		}
			// 	}
			// }
			// /* App.vue */
			// /* 默认状态边框 */
			// /deep/ .u-checkbox__icon-wrap {
			// 	border-color: #000 !important;
			// }
			// /* 选中状态边框 */
			// /deep/ .u-checkbox__icon-wrap--checked {
			// 	border-color: #000 !important;
			// 	background-color: #000 !important;
			// 	/* 如需同步背景色 */
			// }
		}
	}
}
</style>
